<template>
  <div class="analytics-container">
    <div class="query-section">
      <div class="input-group">
        <input 
          type="text" 
          v-model="queryInput" 
          placeholder="输入自然语言查询，例如：显示最近7天各区域的销售额趋势"
          @keypress.enter="executeAnalysis"
        >
        <button @click="executeAnalysis">执行分析</button>
      </div>

      <div class="examples">
        <div 
          v-for="(example, index) in examples" 
          :key="index" 
          class="example-btn"
          @click="setExample(example)"
        >
          {{ example }}
        </div>
      </div>
    </div>

    <div class="results-section">
      <div class="chart-container">
        <div class="section-title">
          <i>📈</i> 数据可视化
        </div>

        <div id="chartStatus" class="chart-status" :style="{ color: chartStatusColor }">
          {{ chartStatusMessage }}
        </div>

        <div class="chart-wrapper">
          <div ref="chartContainer" class="echarts-container"></div>
          <div v-if="!showChart" ref="chartPlaceholder" class="chart-placeholder">
            <i>📊</i>
            <h3>图表将在这里显示</h3>
            <p>输入查询后，AI将自动生成可视化图表</p>
          </div>
        </div>

        <div class="loading" :class="{ active: isProcessing }">
          <div class="spinner"></div>
          <div>正在分析数据，请稍候...</div>
        </div>
      </div>

      <div class="summary-container">
        <div class="section-title">
          <i>💡</i> AI分析总结
        </div>
        <div class="ai-summary" ref="summaryArea">
          <div v-if="!summaryContent" class="placeholder-content">
            <h3>分析结果将显示在这里</h3>
            <p>输入查询后，AI将自动分析数据模式并提供业务洞察</p>
          </div>
          <div v-else v-html="summaryContent"></div>
        </div>

        <div v-if="errorMessage" class="error-container">
          <strong>错误:</strong> {{ errorMessage }}
          <button @click="clearError" class="error-close-btn">
            关闭
          </button>
        </div>

        <div v-if="debugMessages.length > 0" class="debug-info" ref="debugArea">
          <div v-for="(message, index) in debugMessages" :key="index">
            [{{ message.timestamp }}] {{ message.content }}
          </div>
        </div>
      </div>
    </div>

    <div class="status-bar">
      <div>连接状态: <span :style="{ color: connectionStatusColor }">{{ connectionStatusMessage }}</span></div>
      <div>最后更新: <span>{{ lastUpdate }}</span></div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue';
import * as echarts from 'echarts';
import { marked } from 'marked';

// 响应式数据
const queryInput = ref('');
const examples = ref([
  '显示各品牌销售额占比',
  '查询2024年各品牌PTV分析情况',
  '查询2024年库存周转率'
]);
const currentChart = ref(null);
const isProcessing = ref(false);
const abortController = ref(null);
const showChart = ref(false);
const chartStatusMessage = ref('等待查询...');
const chartStatusColor = ref('#666');
const summaryContent = ref('');
const errorMessage = ref('');
const debugMessages = ref([]);
const connectionStatusMessage = ref('未连接');
const connectionStatusColor = ref('#666');
const lastUpdate = ref('--');

// 模板引用
const chartContainer = ref(null);
const chartPlaceholder = ref(null); // 添加缺失的ref
const summaryArea = ref(null);
const debugArea = ref(null);

// 配置 marked
marked.setOptions({
  breaks: true,
  gfm: true,
  tables: true
});

// 设置示例查询
const setExample = (example) => {
  queryInput.value = example;
  executeAnalysis();
};

// 执行分析
const executeAnalysis = async () => {
  if (isProcessing.value) {
    showError('正在处理上一个请求，请稍候...');
    return;
  }

  const query = queryInput.value.trim();
  if (!query) {
    showError('请输入查询内容');
    return;
  }

  // 取消之前的请求
  if (abortController.value) {
    abortController.value.abort();
  }

  // 重置状态
  isProcessing.value = true;
  abortController.value = new AbortController();
  clearError();
  clearChart();
  clearDebug();
  showChart.value = false;
  
  summaryContent.value = '<h3>分析中...</h3><p>正在处理您的查询，请稍候</p>';

  // 更新连接状态
  connectionStatusMessage.value = '连接中...';
  connectionStatusColor.value = '#f39c12';
  updateChartStatus('正在连接服务器...', '#f39c12');
  addDebugInfo(`开始分析: ${query}`);

  try {
    // 连接真实后端API
    const response = await fetch('http://localhost/api/ai/analyze', {
      method: 'POST',
      headers: {'Content-Type': 'application/json'},
      body: JSON.stringify({query, chartType: 'auto'}),
      signal: abortController.value.signal
    });

    if (!response.ok) {
      throw new Error(`HTTP错误: ${response.status}`);
    }

    connectionStatusMessage.value = '已连接';
    connectionStatusColor.value = '#2ecc71';
    updateChartStatus('已连接，正在处理...', '#2ecc71');
    addDebugInfo('服务器连接成功');

     const reader = response.body.getReader();
        const decoder = new TextDecoder();
        let buffer = '';

        while (true) {
            const {done, value} = await reader.read();
            if (done) break;

            buffer += decoder.decode(value, {stream: true});
            const lines = buffer.split('\n');
            buffer = lines.pop() || '';

            for (const line of lines) {
                if (line.startsWith('data:')) {
                    const eventData = line.substring(5).trim();
                    if (eventData) {
                        try {
                            processEvent(JSON.parse(eventData));
                        } catch (e) {
                            console.error('解析事件失败:', e);
                        }
                    }
                }
            }
        }

        isProcessing.value = false; // 修复这里缺少的.value
        addDebugInfo('分析完成');

  } catch (error) {
    if (error.name === 'AbortError') {
            addDebugInfo('请求已取消');
            return;
        }

        console.error('请求失败:', error);
        showError('请求失败: ' + error.message);
        addDebugInfo(`请求失败: ${error.message}`);

        connectionStatusMessage.value = '已断开'; // 修复这里直接访问DOM的错误
        connectionStatusColor.value = '#e74c3c';
        updateChartStatus('连接失败', '#e74c3c');

    // 确保loading状态被重置
    isProcessing.value = false;
  }
};

// 处理事件
const processEvent = (data) => {
  addDebugInfo(`${data.type}: ${data.message || data.step}`);
  
  switch (data.type) {
    case 'chart':
      updateChartStatus('图表已生成', '#2ecc71');
      renderChart(data.data);
      isProcessing.value = false;
      break;
    case 'summary_chunk':
      appendSummaryChunk(data.data);
      break;
    case 'summary_complete':
      updateChartStatus('分析完成', '#2ecc71');
      completeSummary(data.data);
      break;
    case 'error':
      updateChartStatus('处理出错', '#e74c3c');
      showError(data.message);
      // 出错时也重置loading状态
      isProcessing.value = false;
      break;
    case 'status':
      updateChartStatus(data.message, '#3498db');
      break;
    case 'sql':
      updateChartStatus('SQL生成完成', '#3498db');
      break;
    case 'data':
      updateChartStatus('数据查询完成', '#3498db');
      break;
  }

  updateLastUpdate();
};

// 渲染图表
const renderChart = (config) => {
  if (!config) return;
    
  console.log('接收到的图表配置:', config);
    console.log(chartPlaceholder.value, chartContainer.value);
    
    
    if (chartPlaceholder.value && chartContainer.value) {
      chartPlaceholder.value.style.display = 'none';
      chartContainer.value.style.display = 'block';

      const chart = echarts.init(chartContainer.value);

      try {
          const option = buildEChartsOption(config);
          console.log('处理后的图表配置:', option);
          chart.setOption(option, true); // 使用true参数强制更新
          
          // 移除之前的resize事件监听，避免重复添加
          window.removeEventListener('resize', handleResize);
          window.addEventListener('resize', handleResize);
          
          addDebugInfo('图表渲染成功');
          currentChart.value = chart;
      } catch (error) {
          console.error('图表渲染失败:', error);
          showError('图表渲染失败: ' + error.message);
          chartPlaceholder.value.style.display = 'flex';
          chartContainer.value.style.display = 'none';
      }
    }
};

// 修正Markdown格式 - 增强版
const fixMarkdownFormat = (markdown) => {
  if (!markdown || typeof markdown !== 'string') return '';
  
  let fixed = markdown;
    // 1. 修正标题格式：#后加空格，标题间强制换行
    // 先处理#后无空格的情况（在#和文字间加空格）
    fixed = fixed.replace(/#+(\S)/g, (match) => {
        const hashes = match.match(/#+/)[0]; // 提取所有#
        const text = match.slice(hashes.length); // 提取标题文字
        return `${hashes} ${text}`;
    });

    // 修正：在任意两个标题之间添加换行（包括隐藏在文本中的标题）
    // 使用更精确的正则来匹配标题模式（包括三级标题）
    fixed = fixed.replace(/([^#\n])(###? \*\*[^*]+\*\*)/g, '$1\n$2');
    fixed = fixed.replace(/([^#\n])(###? [^\n#]+)/g, '$1\n$2');

    // 处理连续标题的情况
    fixed = fixed.replace(/(#+ [^\n#]+)(#+ [^\n#]+)/g, '$1\n$2');

    // 2. 修正数字列表：确保每个数字列表项单独一行
    fixed = fixed.replace(/(\d+\.\s\*\*[^*]+\*\*[^0-9]+)(?=\d+\.)/g, '$1\n');

    // 3. 修正无序列表：确保每个列表项单独一行，-后有空格
    fixed = fixed.replace(/(\S)(-\s*\*\*)/g, '$1\n$2'); // 在列表项前加换行
    fixed = fixed.replace(/-\s*(\*\*)/g, '- $1'); // 确保-后有空格

    // 4. 修正块引用（>）：确保单独成行，前面有空行
    fixed = fixed.replace(/([^\n])(> \*\*)/g, '$1\n\n$2'); // 在块引用前加空行

    // 5. 修正表格：在表格前添加空行
    fixed = fixed.replace(/(\S)\s*(\|[^]+?\|\s*\|\s*[-|]+\s*\|)/, '$1\n\n$2');

    // 清理格式
    fixed = fixed.replace(/\n{3,}/g, '\n\n').trim();
  
  return fixed;
};

// 构建ECharts配置
const buildEChartsOption = (chartConfig) => {
  // 基础配置，设置居中对齐和偏灰色文字
  const baseOption = {
        title: {text: '数据分析图表', left: 'center'},
        tooltip: {trigger: 'axis'},
        grid: {left: '50px', right: '50px', bottom: '50px', top: '60px'}
    };

    if (typeof chartConfig === 'string') {
        try {
            chartConfig = JSON.parse(chartConfig);
        } catch (e) {
            console.error('解析图表配置失败:', e);
            return baseOption;
        }
    }
    
    // 修复数据中的错误字段
    if (chartConfig.series && Array.isArray(chartConfig.series)) {
      chartConfig.series.forEach(series => {
        if (series.data && Array.isArray(series.data)) {
          series.data.forEach(item => {
            // 修复错误的3value字段
            if (item['3value'] !== undefined) {
              item.value = item['3value'];
              delete item['3value'];
            }
          });
        }
        
        // 为饼图设置正确的tooltip触发器
        if (series.type === 'pie' || series.type === 'doughnut') {
          if (!chartConfig.tooltip) {
            chartConfig.tooltip = {};
          }
          chartConfig.tooltip.trigger = 'item';
        }
      });
    }
    
    // 合并配置时，如果是饼图或仪表盘，移除不需要的grid配置
    const mergedOption = {...baseOption, ...chartConfig};
    if (chartConfig.series && Array.isArray(chartConfig.series) && 
        chartConfig.series.some(s => s.type === 'pie' || s.type === 'doughnut')) {
      delete mergedOption.grid;
    }

    return mergedOption;
};

// 追加分析内容
const appendSummaryChunk = (chunkData) => {
  const fullContent = chunkData.fullContent || '';

    if (fullContent.trim() && summaryArea.value) {
        const markdownFormat = fixMarkdownFormat(fullContent);
        const htmlContent = marked.parse(markdownFormat);

        summaryArea.value.innerHTML = `
            <div class="markdown-content">${htmlContent}</div>
            <div class="streaming-indicator">
                <div class="typing-animation">
                    <span></span><span></span><span></span>
                </div>
                <span>AI正在思考中...</span>
            </div>
        `;
        summaryArea.value.scrollTop = summaryArea.value.scrollHeight;
    }
};

// 完成分析总结
const completeSummary = (completeData) => {
  const fullContent = completeData.fullContent || '';
    if (fullContent.trim() && summaryArea.value) {
        const markdownFormat = fixMarkdownFormat(fullContent);
        const htmlContent = marked.parse(markdownFormat);

        summaryArea.value.innerHTML = `
            <div class="markdown-content">${htmlContent}</div>
            <div style="margin-top: 20px; padding-top: 15px; border-top: 1px dashed #eee; color: #7f8c8d; font-size: 14px;">
                <i>提示：以上分析由AI生成，仅供参考</i>
            </div>
        `;
        
        summaryArea.value.scrollTop = summaryArea.value.scrollHeight;
    }
};

// 清理图表
const clearChart = () => {
  if (chartContainer.value) {
    chartContainer.value.style.display = 'none';
    const chart = echarts.getInstanceByDom(chartContainer.value);
    if (chart) chart.dispose();
  }
  
  if (chartPlaceholder.value) {
    chartPlaceholder.value.style.display = 'flex';
  }
  
  currentChart.value = null;
};

// 更新图表状态
const updateChartStatus = (message, color) => {
  chartStatusMessage.value = message;
  chartStatusColor.value = color;
};

// 显示错误
const showError = (message) => {
  errorMessage.value = message;
};

// 清除错误
const clearError = () => {
  errorMessage.value = '';
};

// 添加调试信息
const addDebugInfo = (message) => {
  const timestamp = new Date().toLocaleTimeString();
  debugMessages.value.push({ timestamp, content: message });

  // 限制调试信息行数
  if (debugMessages.value.length > 15) {
    debugMessages.value = debugMessages.value.slice(-15);
  }

  // 滚动到底部
  if (debugArea.value) {
    debugArea.value.scrollTop = debugArea.value.scrollHeight;
  }
};

// 清除调试信息
const clearDebug = () => {
  debugMessages.value = [];
};

// 更新最后更新时间
const updateLastUpdate = () => {
  lastUpdate.value = new Date().toLocaleTimeString();
};

// 窗口大小变化处理
const handleResize = () => {
  if (currentChart.value) {
    currentChart.value.resize();
  }
};

// 生命周期钩子
onMounted(() => {
  updateLastUpdate();
  window.addEventListener('resize', handleResize);
  
  // 移除自动显示示例图表的代码
  // 组件将保持初始状态，等待用户输入查询或点击示例按钮
});
onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize);
  if (currentChart.value) {
    currentChart.value.dispose();
  }
});
</script>

<style scoped>
.analytics-container {
  width: 100%;
  height: calc(100vh - 87px);
  display: flex;
  flex-direction: column;
  background-color: rgba(0, 15, 30, 0.95);
  border-radius: 0;
  overflow: hidden;
  position: relative;
}

.query-section {
  padding: 15px 20px;
  border-bottom: 1px solid rgba(7, 96, 197, 0.3);
  flex-shrink: 0;
  background: rgba(0, 21, 41, 0.5);
}

.input-group {
  display: flex;
  gap: 15px;
  width: 100%;
  max-width: 1200px;
  margin: 0 auto;
}

.input-group input {
  flex: 1;
  padding: 12px 16px;
  border: 1px solid rgba(50, 240, 140, 0.3);
  border-radius: 25px;
  font-size: 14px;
  transition: all 0.3s ease;
  background-color: rgba(0, 15, 30, 0.7);
  color: white;
  backdrop-filter: blur(5px);
}

.input-group input::placeholder {
  color: rgba(255, 255, 255, 0.5);
}

.input-group input:focus {
  outline: none;
  border-color: #32f08c;
  box-shadow: 0 0 20px rgba(50, 240, 140, 0.3);
  background-color: rgba(0, 15, 30, 0.9);
}

.input-group button {
  background: linear-gradient(135deg, #0760c5, #32f08c);
  color: white;
  border: none;
  border-radius: 25px;
  padding: 0 20px;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  white-space: nowrap;
  min-width: 100px;
}

.input-group button:hover {
  transform: translateY(-1px);
  box-shadow: 0 8px 20px rgba(50, 240, 140, 0.3);
}

.examples {
  margin-top: 12px;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  justify-content: center;
}

.example-btn {
  background: rgba(0, 15, 30, 0.6);
  border: 1px solid rgba(50, 240, 140, 0.3);
  border-radius: 20px;
  padding: 5px 12px;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s ease;
  color: white;
  backdrop-filter: blur(5px);
}

.example-btn:hover {
  background: rgba(50, 240, 140, 0.1);
  border-color: #32f08c;
  box-shadow: 0 0 8px rgba(50, 240, 140, 0.2);
  transform: translateY(-1px);
}

.results-section {
  display: flex;
  flex: 1;
  min-height: 0;
  overflow: hidden;
  background-color: rgba(0, 15, 30, 0.6);
  position: relative;
  gap: 1px;
  background-image: linear-gradient(90deg, transparent, transparent 50px, rgba(50, 240, 140, 0.05) 50px, rgba(50, 240, 140, 0.05) 51px);
}

.chart-container {
  flex: 2;
  padding: 20px;
  border-right: 1px solid rgba(7, 96, 197, 0.3);
  position: relative;
  display: flex;
  flex-direction: column;
  backdrop-filter: blur(5px);
}

.summary-container {
  flex: 2;
  padding: 20px;
  background: rgba(0, 15, 30, 0.3);
  display: flex;
  flex-direction: column;
  min-height: 0;
  backdrop-filter: blur(5px);
}

.section-title {
  font-size: 14px;
  font-weight: 600;
  color: white;
  margin-bottom: 12px;
  display: flex;
  align-items: center;
}

.section-title i {
  margin-right: 8px;
  font-size: 16px;
  color: #32f08c;
}

.chart-wrapper {
  flex: 1;
  position: relative;
  min-height: 0;
  background: rgba(0, 15, 30, 0.5);
  background-image: 
    linear-gradient(rgba(50, 240, 140, 0.1) 1px, transparent 1px),
    linear-gradient(90deg, rgba(50, 240, 140, 0.1) 1px, transparent 1px);
  background-size: 20px 20px;
  border-radius: 8px;
  overflow: hidden;
  border: 1px solid rgba(50, 240, 140, 0.2);
  box-shadow: 0 0 20px rgba(7, 96, 197, 0.1);
  display: flex;
  justify-content: center;
  align-items: center;
}

.echarts-container {
  width: 100%;
  height: 100%;
  min-height: 400px;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

.chart-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #999;
  text-align: center;
  padding: 40px;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 1;
}

.ai-summary {
  background: rgba(0, 15, 30, 0.6);
  border-radius: 8px;
  padding: 16px;
  border: 1px solid rgba(50, 240, 140, 0.2);
  line-height: 1.6;
  font-size: 14px;
  color: white;
  flex: 1;
  overflow-y: auto;
  min-height: 0;
  backdrop-filter: blur(5px);
}

.ai-summary::-webkit-scrollbar {
  width: 8px;
}

.ai-summary::-webkit-scrollbar-track {
  background: rgba(0, 21, 41, 0.3);
  border-radius: 4px;
}

.ai-summary::-webkit-scrollbar-thumb {
  background: rgba(50, 240, 140, 0.5);
  border-radius: 4px;
  transition: background 0.3s ease;
}

.ai-summary::-webkit-scrollbar-thumb:hover {
  background: rgba(50, 240, 140, 0.8);
}

.debug-info {
  margin-top: 10px;
  padding: 8px;
  background: rgba(0, 21, 41, 0.8);
  border-radius: 4px;
  font-size: 11px;
  color: #32f08c;
  max-height: 80px;
  overflow-y: auto;
}

.debug-info::-webkit-scrollbar {
  width: 6px;
}

.debug-info::-webkit-scrollbar-track {
  background: rgba(0, 21, 41, 0.5);
  border-radius: 3px;
}

.debug-info::-webkit-scrollbar-thumb {
  background: rgba(50, 240, 140, 0.4);
  border-radius: 3px;
}

.debug-info > div {
  margin-bottom: 2px;
}

.chart-placeholder h3 {
  margin-bottom: 10px;
  font-size: 16px;
  color: #999;
}

.chart-placeholder p {
  font-size: 14px;
  opacity: 0.8;
  color: #666;
}

.loading {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 15, 30, 0.95);
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  z-index: 10;
  border-radius: 8px;
  opacity: 0;
  pointer-events: none;
  transition: opacity 0.3s;
  backdrop-filter: blur(10px);
}

.loading.active {
  opacity: 0.8;
  pointer-events: all;
}

.spinner {
  width: 40px;
  height: 40px;
  border: 3px solid rgba(50, 240, 140, 0.1);
  border-top: 3px solid #32f08c;
  border-radius: 50%;
  animation: spin 1.5s linear infinite;
  margin-bottom: 15px;
  box-shadow: 0 0 15px rgba(50, 240, 140, 0.3);
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.error-container {
  background: rgba(231, 76, 60, 0.2);
  border: 1px solid #e74c3c;
  border-radius: 8px;
  padding: 12px;
  margin-top: 12px;
  color: #e74c3c;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.error-close-btn {
  padding: 2px 8px;
  background: #e74c3c;
  color: white;
  border: none;
  border-radius: 3px;
  cursor: pointer;
  font-size: 12px;
}

.status-bar {
  padding: 10px 20px;
  background: rgba(0, 15, 30, 0.8);
  border-top: 1px solid rgba(50, 240, 140, 0.2);
  font-size: 12px;
  color: rgba(255, 255, 255, 0.8);
  display: flex;
  justify-content: space-between;
  flex-shrink: 0;
  backdrop-filter: blur(5px);
}

.status-bar span {
  color: #32f08c;
  font-weight: 500;
}

.chart-status {
  margin-bottom: 12px;
  padding: 6px 8px;
  background: rgba(7, 96, 197, 0.2);
  border-radius: 6px;
  font-size: 12px;
}

.debug-info {
  margin-top: 10px;
  padding: 8px;
  background: rgba(0, 21, 41, 0.8);
  border-radius: 4px;
  font-size: 11px;
  color: #32f08c;
  max-height: 80px;
  overflow-y: auto;
}

.debug-info > div {
  margin-bottom: 2px;
}

.ai-summary {
  background: rgba(0, 15, 30, 0.6);
  border-radius: 8px;
  padding: 16px;
  border: 1px solid rgba(50, 240, 140, 0.2);
  line-height: 1.6;
  font-size: 14px;
  color: white;
  flex: 1;
  overflow-y: auto;
  min-height: 0;
  backdrop-filter: blur(5px);
}

.ai-summary h3 {
  color: #32f08c;
  margin-bottom: 10px;
  font-size: 16px;
}

.placeholder-content h3 {
  color: #32f08c;
  margin-bottom: 10px;
  font-size: 16px;
}

.placeholder-content p {
  opacity: 0.8;
  font-size: 14px;
}

/* Markdown 样式 */
:deep(.markdown-content) {
  line-height: 1.6;
  font-size: 14px;
}

:deep(.markdown-content h1) {
  color: white;
  font-size: 1.3em;
  border-bottom: 2px solid #0760c5;
  padding-bottom: 8px;
  margin: 1em 0 0.8em 0;
}

:deep(.markdown-content h2) {
  color: white;
  font-size: 1.2em;
  border-left: 4px solid #32f08c;
  padding-left: 10px;
  margin: 1em 0 0.7em 0;
}

:deep(.markdown-content h3) {
  color: #32f08c;
  font-size: 1.1em;
  margin: 0.9em 0 0.5em 0;
}

:deep(.markdown-content p) {
  margin-bottom: 0.8em;
}

:deep(.markdown-content ul),
:deep(.markdown-content ol) {
  margin: 0.8em 0;
  padding-left: 1.5em;
}

:deep(.markdown-content li) {
  margin-bottom: 0.4em;
}

:deep(.markdown-content blockquote) {
  border-left: 4px solid #0760c5;
  padding: 10px 14px;
  margin: 1.2em 0;
  background: rgba(7, 96, 197, 0.2);
  border-radius: 0 6px 6px 0;
  font-style: italic;
}

:deep(.markdown-content code) {
  background: rgba(50, 240, 140, 0.2);
  padding: 2px 5px;
  border-radius: 4px;
  font-family: 'Consolas', 'Monaco', monospace;
  font-size: 0.85em;
  color: #32f08c;
}

:deep(.markdown-content pre) {
  background: #2c3e50;
  color: #ecf0f1;
  padding: 12px;
  border-radius: 6px;
  overflow-x: auto;
  margin: 1.2em 0;
  font-family: 'Consolas', 'Monaco', monospace;
  font-size: 0.85em;
  line-height: 1.4;
}

:deep(.markdown-content pre code) {
  background: none;
  padding: 0;
  color: inherit;
  font-size: inherit;
}

:deep(.markdown-content table) {
  width: 100%;
  border-collapse: collapse;
  margin: 1.2em 0;
  font-size: 0.9em;
  overflow-x: auto;
  display: block;
}

:deep(.markdown-content th) {
  background: #0760c5;
  color: white;
  font-weight: 600;
  padding: 8px;
  text-align: left;
}

:deep(.markdown-content td) {
  padding: 8px;
  border-bottom: 1px solid #0760c5;
  color: white;
}

:deep(.markdown-content tr:nth-child(even)) {
  background: rgba(7, 96, 197, 0.2);
}

/* 流式输出指示器 */
:deep(.streaming-indicator) {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-top: 12px;
  padding: 8px;
  background: rgba(7, 96, 197, 0.2);
  border-radius: 6px;
  font-size: 12px;
}

:deep(.typing-animation) {
  display: flex;
  gap: 3px;
}

:deep(.typing-animation span) {
  height: 6px;
  width: 6px;
  background: #32f08c;
  border-radius: 50%;
  animation: typing 1.4s infinite ease-in-out;
}

:deep(.typing-animation span:nth-child(1)) {
  animation-delay: 0s;
}

:deep(.typing-animation span:nth-child(2)) {
  animation-delay: 0.2s;
}

:deep(.typing-animation span:nth-child(3)) {
  animation-delay: 0.4s;
}

@keyframes typing {
  0%, 60%, 100% {
    transform: scale(0.8);
    opacity: 0.5;
  }
  30% {
    transform: scale(1);
    opacity: 1;
  }
}

/* 响应式调整 */
@media (max-width: 768px) {
  .results-section {
    flex-direction: column;
  }
  
  .chart-container,
  .summary-container {
    min-height: 400px;
  }
  
  .input-group {
    flex-direction: column;
  }
  
  .input-group button {
    padding: 12px 20px;
  }
}
</style>